<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="box"></div>
    <script>
      const box = document.getElementById("box");
      const users = [
        { id: 1, name: "jack", age: 20, gender: "boy" },
        { id: 2, name: "lili", age: 21, gender: "girl" },
        { id: 3, name: "lucy", age: 19, gender: "girl" },
        { id: 4, name: "tom", age: 22, gender: "boy" },
      ];

      function renderTable(data) {
        const rows = data
          .map((el) => {
            return `
              <tr>
                <td>${el.id}</td>
                <td>${el.name}</td>
                <td>${el.age}</td>
                <td>${el.gender}</td>
              </tr>
              `;
          })
          .join("");
        return `
        <table border="1px">
          <thead>
            <tr>
              <th>编号</th>
              <th>姓名</th>
              <th>年龄</th>
              <th>性别</th>
            </tr>
          </thead>
          <tbody>
            ${rows}
          </tbody>
        </table>
        `;
      }

      // 基于年龄排序
      // users.sort((a, b) => (a.age > b.age ? 1 : -1));

      // 基于姓名排序
      users.sort((a, b) => (a.name < b.name ? 1 : -1));

      box.innerHTML = renderTable(users);
    </script>
  </body>
</html>
